package cn.hfatec.shms.web.yk.ykOrder.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.service.OrganizationService;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzbParams;
import cn.hfatec.shms.web.yk.ykGather.model.YkGatherParams;
import cn.hfatec.shms.web.yk.ykGather.service.YkGatherService;
import cn.hfatec.shms.web.yk.ykOrder.model.YkOrder;
import cn.hfatec.shms.web.yk.ykOrder.model.YkOrderParams;
import cn.hfatec.shms.web.yk.ykOrder.service.YkOrderService;
import cn.hfatec.shms.web.yk.ykType.service.YkTypeService;
import cn.hfatec.shms.web.yk.ykUser.model.YkUser;
import cn.hfatec.shms.web.yk.ykUser.service.YkUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/yk/ykOrder")
public class YkOrderAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "YkOrderService")
    private YkOrderService ykOrderService;
    //服务层
    @Resource(name = "YkTypeService")
    private YkTypeService ykTypeService;

    //服务层
    @Resource(name = "YkUserService")
    private YkUserService ykUserService;
    //服务层
    @Resource(name = "YkGatherService")
    private YkGatherService ykGatherService;

    //服务层
    @Resource(name = "OrganizationService")
    private OrganizationService organizationService;

    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(YkOrderParams ykOrderParams, Page page, Model model) {
        if (ykOrderParams != null  ) {
            if(ykOrderParams.getSpareG()!=null){
            if (ykOrderParams.getSpareG().equals("0")) {
                ykOrderParams.setSpareF("0");
            }
        }}
        Table table = ykOrderService.queryYkOrderTable(ykOrderParams, page);
        YkOrder ykOrder=ykOrderService.hjYkOrder(ykOrderParams);
        model.addAttribute("ykOrderHj", ykOrder);
        model.addAttribute("ykOrdersTable", table);
        model.addAttribute("ykOrderParams", ykOrderParams);
        model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
        model.addAttribute("productTypeList", CodeInfoCache.getCodeInfo(CodeType.JKGL_TYPE));
        model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
        model.addAttribute("vipBackTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
        model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
        model.addAttribute("vipqdTypeList", CodeInfoCache.getCodeInfo(CodeType.VIPQD_TYPE));
        return "/yk/ykOrder/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(YkOrderParams ykOrderParams, Page page, Model model) {
        try {

            list(ykOrderParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykOrder/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            YkOrder ykOrder = new YkOrder();
            List ykGather = ykGatherService.getYkGatherList();
            model.addAttribute("ykGatherList", ykGather);
            model.addAttribute("ykOrder", ykOrder);
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("costTypeList", CodeInfoCache.getCodeInfo(CodeType.COST_TYPE));
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("vipBackTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            model.addAttribute("vipqdTypeList", CodeInfoCache.getCodeInfo(CodeType.VIPQD_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykOrder/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            YkOrder ykOrder = ykOrderService.getYkOrder(id);
            YkGatherParams ykGatherParams = new YkGatherParams();
            ykGatherParams.setBillId(ykOrder.getBillId());
            List ykGather = ykGatherService.getYkGatherList(ykGatherParams);
            model.addAttribute("ykOrder", ykOrder);
            model.addAttribute("ykGatherList", ykGather);
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("costTypeList", CodeInfoCache.getCodeInfo(CodeType.COST_TYPE));
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("vipBackTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            model.addAttribute("vipqdTypeList", CodeInfoCache.getCodeInfo(CodeType.VIPQD_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykOrder/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteYkOrder(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            ykOrderService.deleteYkOrderBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveYkOrder(String[] ids, String[] gatherType, String[] gatherMoney, @Valid YkOrder ykOrder, BindingResult result, HttpServletRequest request) {

        try {
            User user = (User) request.getSession().getAttribute(SysContant.LOGIN_USER_SESSION);
            if (user == null) {
                throw new NotAuthException("用户未授权");
            } else {
                Organization organization = organizationService.getOrganizationByOrgId(user.getOrgId());
                ykOrder.setSpareB(organization.getOrgLevelCode());
            }
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            ykOrderService.saveYkOrder(ykOrder, ids, gatherType, gatherMoney, user);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据YkOrder保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goFind")
    @ResponseBody
    public String goFind(String staffId, Model model) {
        try {
            YkUser ykUser = ykUserService.getYkUserStaffId(staffId);
            YkOrder ykOrder = new YkOrder();
            if (ykUser == null) {
                ykOrder = ykOrderService.getXh(staffId);
                if (ykOrder == null) {
                    ykOrder = new YkOrder();
                }
                ykOrder.setSpareA("0");
            } else {
                ykOrder.setUserId(ykUser.getUserId());
                ykOrder.setCardId(ykUser.getCardId());
                ykOrder.setCustomerName(ykUser.getUserName());
                ykOrder.setAge(ykUser.getAge());
                ykOrder.setSex(ykUser.getSex().toString());
                ykOrder.setAddress(ykUser.getAddress());
                ykOrder.setPhone(ykUser.getPhone());
                ykOrder.setSpareA("1");
            }


            YkOrder ykyyh = ykOrderService.getYkOrderstaffId(staffId);
            if (ykyyh != null) {
                ykOrder.setRecordNo(ykyyh.getRecordNo());
            }
            ykOrder.setStaffId(staffId);


            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("costTypeList", CodeInfoCache.getCodeInfo(CodeType.COST_TYPE));
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("vipBackTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            model.addAttribute("vipqdTypeList", CodeInfoCache.getCodeInfo(CodeType.VIPQD_TYPE));
            model.addAttribute("ykOrder", ykOrder);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykOrder/order", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goYkType")
    @ResponseBody
    public String goYkType(Integer id, Model model) {
        try {
            YkOrder ykOrder = ykOrderService.getYkType(id);
            if (ykOrder != null) {
                if (!"".equals(ykOrder.getCostType()) && !"".equals(ykOrder.getCostMoney()) && !"".equals(ykOrder.getMoney()) && ykOrder.getCostType() != null && ykOrder.getCostMoney() != null && ykOrder.getMoney() != null) {
                    if (ykOrder.getCostType().equals("1")) {
                        ykOrder.setCost(ykOrder.getCostMoney());
                    } else if (ykOrder.getCostType().equals("2")) {
                        String cost = String.valueOf(Double.valueOf(ykOrder.getCostMoney()) * Double.valueOf(ykOrder.getMoney()));
                        ykOrder.setCost(cost);
                    }
                }
            }
            model.addAttribute("ykOrder", ykOrder);
            model.addAttribute("vipTypeList", CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE));
            model.addAttribute("costTypeList", CodeInfoCache.getCodeInfo(CodeType.COST_TYPE));
            model.addAttribute("sexTypeList", CodeInfoCache.getCodeInfo(CodeType.SEX));
            model.addAttribute("vipBackTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            model.addAttribute("channelTypeList", CodeInfoCache.getCodeInfo(CodeType.CHANNEL_TYPE));
            model.addAttribute("vipqdTypeList", CodeInfoCache.getCodeInfo(CodeType.VIPQD_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykOrder/yktype", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goBlur")
    @ResponseBody
    public String goBlur(Date billStart, Integer vipCycle) {
        try {
            YkOrder ykOrder = new YkOrder();
            Date dt = billStart;
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, vipCycle);
            Date enddate = rightNow.getTime();
            ykOrder.setBillEnd(enddate.toString());
            if (billStart != null) {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", ykOrder).toString();
            } else {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", new YkOrder()).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 导入潜在客户
     *
     * @param path
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/importOrder")
    @ResponseBody
    public String importCustom(String path, HttpServletRequest request, HttpServletResponse response) {

        try {

            return ykOrderService.importCust(path, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Custom保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
    }

    /**
     * 导入模板下载
     *
     * @param request
     * @param response
     * @param serverFileName
     * @param clientFileName
     * @return
     */
    @RequestMapping("/downloadTemplate")
    @ResponseBody
    public String downloadTemplate(HttpServletRequest request, HttpServletResponse response, String serverFileName, String clientFileName) {
        FileInputStream fileInputStream = null;
        String msg = "";
        try {

            File file = new File(request.getSession().getServletContext().getRealPath("") + File.separator + "WEB-INF" + File.separator + "content" + File.separator + "yk" + File.separator + "ykOrder" + File.separator + serverFileName);

            long fileLength = file.length();

            // 设置下载参数
            clientFileName = encodeFilename(request, clientFileName);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName);
            response.addHeader("Content-Length", "" + fileLength);
            response.setContentType("application/octet-stream;charset=UTF-8");
            // response.setContentType("application/x-msdownload");

            fileInputStream = new FileInputStream(file);
            OutputStream out = response.getOutputStream();

            // 读文件
            int iBufferSize = 65000;
            byte[] buffer = new byte[65000];
            long lReadLen = 0;
            while (lReadLen < fileLength) {
                int lRead = fileInputStream.read(buffer, 0, iBufferSize);
                lReadLen += lRead;
                out.write(buffer, 0, lRead);
            }
            out.flush();

        } catch (Exception e) {
            logger.error("下载文件失败!", e);
            msg = "下载文件失败!<a href='#' onclick='javascript:history.go(-1);'>返回</a><br/>";
            msg += e.getMessage();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
        }

        return msg;
    }

    /**
     * 导出excel
     */
    @RequestMapping("/export")
    @ResponseBody
    public String export(YkOrderParams ykOrderParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (ykOrderParams != null  ) {
                if(ykOrderParams.getSpareG()!=null){
                    if (ykOrderParams.getSpareG().equals("0")) {
                        ykOrderParams.setSpareF("0");
                    }
                }}
            ykOrderService.exportExcel(ykOrderParams, request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
